﻿import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text } from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import './confirmorder.scss'
export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      arr: [],
      receipt: {},
      youfui: 0,
      yunfei: '包邮',
      getadress: false,//判断是否重新请求地址刷新  获取邮费
      adressId:0,
      freetype:0,
      orderId:0,
      zftype:0,
      paypwd:[],
      paypwdlen:0,
      tuitable:[{number:'1',tuibg:false,innerhtml:false,click:'1'},
                {number:'2',tuibg:false,innerhtml:false,click:'1'},
                {number:'3',tuibg:false,innerhtml:false,click:'1'},
                {number:'4',tuibg:false,innerhtml:false,click:'1'},
                {number:'5',tuibg:false,innerhtml:false,click:'1'},
                {number:'6',tuibg:false,innerhtml:false,click:'1'},
                {number:'7',tuibg:false,innerhtml:false,click:'1'},
                {number:'8',tuibg:false,innerhtml:false,click:'1'},
                {number:'9',tuibg:false,innerhtml:false,click:'1'},
                {number:'-',tuibg:true,innerhtml:false,click:'3'},
                {number:'0',tuibg:false,innerhtml:false,click:'1'},
                {number:'',tuibg:true,innerhtml:true,click:'2'}
              ],
      bmtetlist:[{touimg:'https://minichat.g2ma.com/kedouimg/icon26.png',touname:'推荐微信用户使用',toutype:'微信支付',toucheck:true,id:'1'},
                 {touimg:'https://minichat.g2ma.com/kedouimg/icon28.png',touname:'使用我的余额支付',toutype:'余额支付',toucheck:false,id:'2'},
                ],
      paytypes:1,
      totalAmount:0,
      shareUid:''
    }
  }
  config = {
    navigationBarTitleText: '确认订单'
  }

  componentWillMount () {
    let _this = this
    let aar = _this.$router.preload.aar
    let freetype = _this.$router.preload.freetype
    if (freetype) {
      _this.setState({
        arr: aar,
        freetype: freetype
      })
    } else {
      _this.setState({
        arr: aar
      })
    }
    _this.getaddress()
  }
  componentDidShow () {
    //选择地址完成返回重新刷新
    // console.log(JSON.stringify(this.$scope.data))
    let data = this.$scope.data
    let getadress = data.getadress
    // console.log(ischange)
    if (getadress) {
      let id = data.adressId
      // console.log(projectId+'////projectId2222')
      this.setAddr(id)
      this.setState({
        getadress: false
      })
    }
  }
  componentWillUnmount () {
  }
  opendetails(url, type){
    var _this = this
    _this.$preload({
      type: type
    })
    CommonJs.openTo(url)
  }
  price(price){
    //单价
    let prices = parseFloat(price)
    let pricey = prices.toFixed(2)
    return pricey
  }
  totalPrice(price,amount){
    //应付金额(只计算单个，如加上购物车功能此方法不可用)
    let prices = parseFloat(price)
    let amounts =  parseFloat(amount)
    let totalprices = prices * amounts
    let totalpricey = totalprices.toFixed(2)
    return totalpricey
  }
  chooseAddress(){
    //选择地址(暂时不可用)
    Taro.chooseAddress({
      success(res) {
        console.log(res.userName)
        console.log(res.postalCode)
        console.log(res.provinceName)
        console.log(res.cityName)
        console.log(res.countyName)
        console.log(res.detailInfo)
        console.log(res.nationalCode)
        console.log(res.telNumber)
      }
    })
  }
  getPostage(cityId){
    //计算邮费(只计算单个，如加上购物车功能此方法不可用)
    var _this = this
    var arr = _this.state.arr
    var date = {
      cityId:cityId,
      commodityIds:arr[0].commodityId,
      goodsIds:arr[0].id,
      amounts:arr[0].amount,
      shopId:arr[0].shopId
    }
    CommonJs.ajaxRequest('/order/calcPostage',date,'GET',function(res){
      // console.log(JSON.stringify(res)+'mmmmmmmmmmmmmmmmmmm')
      if (res.code != '300' && res.content != null) {
        if (res.content.postage == 0) {
          _this.setState({
            youfei: 0,
            yunfei: '包邮'
          })
        } else {
          _this.setState({
            youfei: res.content.postage,
            yunfei: res.content.postage+'元'
          })                     
        }
      }
    })
  }
  getaddress(){
    //获取全部收货地址，然后默认第一个
    var _this = this
    var date={}
    CommonJs.ajaxRequest('/consume/getAddressListByAccountId',date,'GET',function(res){
      // console.log(JSON.stringify(res)+'你你你你你你你')
      // _this.setAddr(550)
      if (res) {
        if (res.length>0) {
          _this.setAddr(res[0].id) 
        } else {
          Taro.showModal({
            title: '提示',
            content: '你还没有收货地址，请新增选择一个地址',
            showCancel: false,
            success(res){
              _this.opendetails('/pages/my/address',1)
            } 
          })
        }
      }
    })
  }
  setAddr(id){
    var _this = this
    var date={
      id: id
    }
    CommonJs.ajaxRequest('/commerceinfor/getAddressById',date,'GET',function(res){
      // console.log(JSON.stringify(res)+'嗡嗡嗡嗡嗡嗡')
      if (res) {
        if (res.code != 300) {
          _this.setState({
            receipt: res.content
          })
          _this.getPostage(res.content.cityId)
        }
      }
    })
  }
  getcode(){
    var _this = this
    var obj = JSON.stringify(_this.state.receipt)
    if (obj == '{}') {
      Taro.showToast({
        title:'亲，要选择收货地址哦~~',
        icon: 'none',
        duration: 2000
      })
    } else {
      var paytypes = _this.state.paytypes
      if (paytypes == 1) {
        Taro.login({
          success(res) {
            // console.log(JSON.stringify(res)+'aa1111')
            if (res.code) {
                _this.orderSubmit(res.code)
            } else {
                Taro.showToast({
                  title:'网络异常',
                  icon: 'none',
                  duration: 2000
                })
            }
          }
        })
      } else if (paytypes == 2) {
        _this.orderSubmit('')
      }
    }
  }
  orderSubmit(code){
    //提交订单(只支持单独购直接购买，如加上购物车或者PK购功能此方法不可用请用另外接口判断)
    var _this = this
    var receipt = _this.state.receipt
    var arr = _this.state.arr
    var amount = parseFloat(arr[0].amount)
    var price = parseFloat(arr[0].price)
    var postage = parseFloat(_this.state.youfui)
    var freetype = _this.state.freetype
    if (freetype == 1) {
      //pk购
      var url = '/order/createFreeOrder'
      var shareUid = ''
      if (arr[0].shareUid == undefined) {
        shareUid = ''
      } else {
        shareUid = arr[0].shareUid
      }
      var date = {
        addressId: receipt.id,
        dealerId: arr[0].dealerId,
        dealerName: arr[0].dealerName,
        payTypeId: 1,
        businessType: 4,
        orderTypeId: 1,//默认物流配送
        commodityId: arr[0].commodityId,
        commodityName: arr[0].commodityName,
        shopId: arr[0].shopId,
        shopName: arr[0].shopName,
        goodsId: arr[0].id,
        goodsName: arr[0].goodsName,
        amount: amount,
        price: price,
        postage: postage,
        shopCommodityId: arr[0].shopCommodityId,
        clusterId: arr[0].clusterId,
        shareUid: shareUid
      }
    } else {
      //单独购
      var url = '/order/createOrder'
      var date = {
        addressId: receipt.id,
        dealerId: arr[0].dealerId,
        dealerName: arr[0].dealerName,
        payTypeId: 1,
        businessType: 1,
        orderTypeId: 1,//默认物流配送
        commodityId: arr[0].commodityId,
        commodityName: arr[0].commodityName,
        shopId: arr[0].shopId,
        shopName: arr[0].shopName,
        goodsId: arr[0].id,
        goodsName: arr[0].goodsName,
        amount: amount,
        price: price,
        postage: postage
      }
    }
    // console.log(freetype+'////'+JSON.stringify(date))
    CommonJs.ajaxRequest(url,date,'GET',function(res){
      // console.log(JSON.stringify(res)+'wwwwwweeeeeee')
      if (res) {
        if (res.code != '300' && res.content != null) {
          Taro.hideLoading()
          //只支持单独购加商品  如有购物车功能请循环此数据
          var paytypes = _this.state.paytypes
          var content = res.content
          var orderId = content[0].id
          var payAmount = parseFloat(content[0].totalAmount)
          var shareUid = res.content[0].shareUid
          if (paytypes == 1) {
            _this.setState({
              shareUid: shareUid
            })
            _this.pay(orderId, payAmount, code)
          } else if (paytypes == 2) {
            _this.setState({
              zftype:1,
              paypwd:[],
              paypwdlen:0,
              orderId:orderId,
              totalAmount:payAmount,
              shareUid: shareUid
            })
          }
        } else {
          Taro.hideLoading()
          Taro.showToast({
            title:res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    },'','noret','hideLoad')
  }
  pay(orderId, payAmount, code){
    var _this=this
    var paytypes = _this.state.paytypes
    if (paytypes == 1) {
      var date = {
        amounts:payAmount,
        orderIds:orderId,
        payTypeId:125,
        code: code
      }
    } else if (paytypes == 2) {
      var payPasswords = _this.state.paypwd
      var payPassword = payPasswords.join('')
      var date = {
        payPassword:payPassword,
        orderIds:orderId,
        payTypeId:10,
        amounts:payAmount
      }
    }
    // console.log(JSON.stringify(date)+'//3333333333')
    Taro.showLoading({title: '支付中',mask: true})
    CommonJs.ajaxRequest('/order/payOrders',date,'GET',function(ret){
        // console.log(JSON.stringify(ret)+'//444444')
        if (paytypes == 1) {
          Taro.requestPayment({
            timeStamp: ret.content.outret.timeStamp,
            nonceStr: ret.content.outret.nonceStr,
            package: ret.content.outret.packageValue,
            signType: ret.content.outret.signType,
            paySign: ret.content.outret.paySign,
            success(res) {
              _this.gettozuan(orderId, payAmount)
            },
            fail() {
              Taro.showToast({
                title:'支付失败',
                icon: 'none',
                duration: 2000
              })
            }
          })
        } else if (paytypes == 2) {
          // console.log(JSON.stringify(ret)+'1111')
          if (ret) {
            if (ret.code != 300) {
              Taro.hideLoading()
              Taro.showToast({
                title:'支付成功',
                icon: 'success',
                duration: 1500,
                mask: true
              })
              setTimeout(() => {
                var freetype = _this.state.freetype
                if (freetype == 1) {
                  Taro.navigateBack({ delta: 2 })
                  _this.$preload({
                    shareUid: _this.state.shareUid
                  })
                  CommonJs.openTo('/pages/pkgo/invitepk')
                } else {
                  CommonJs.open('/pages/my/unpaid2')
                } 
              }, 1500)
            } else {
              Taro.hideLoading()
              Taro.showModal({
                title: '支付结果',
                content: ret.msg+'，订单已提交，请前往我的订单进行支付',
                showCancel: false,
                confirmText: '确定',
                success:function(res){
                  // console.log(JSON.stringify(res)
                  if (res.confirm) {
                    _this.setState({
                      paypwd:[],
                      paypwdlen:0
                    },function(){
                      CommonJs.open('/pages/my/unpaid')
                      // var freetype = _this.state.freetype
                      // if (freetype == 1) {
                      //   _this.$preload({
                      //     shareUid: _this.state.shareUid
                      //   })
                      //   CommonJs.open('/pages/pkgo/invitepk')
                      // } else {
                      //   CommonJs.open('/pages/my/unpaid2')
                      // } 
                    })
                  }
                }
              })
            }
          }
        }
    },'noloading','noret','hideLoad')
  }
  gettozuan(orderId, payAmount){
    var _this = this
    var date = {
      amounts:payAmount,
      orderIds:orderId
    }
    CommonJs.ajaxRequest('/order/payThePostProcessing',date,'GET',function(ret){
        // console.log(JSON.stringify(ret)+'//444444')
        var freetype = _this.state.freetype
        if (freetype == 1) {
          Taro.navigateBack({ delta: 2 })
          _this.$preload({
            shareUid: _this.state.shareUid
          })
          CommonJs.openTo('/pages/pkgo/invitepk')
        } else {
          CommonJs.open('/pages/my/unpaid2')
        }
    })
  }
  payment(event){
    var _this = this
    // console.log(JSON.stringify(event))
    var checked = event.currentTarget.dataset.type
    var bmtetlist = _this.state.bmtetlist//获取Json数组
    for (var i = 0; i < bmtetlist.length;i++){
      if (bmtetlist[i].id == checked){
        bmtetlist[i].toucheck = true;//当前点击的位置为true即选中
      }
      else{
        bmtetlist[i].toucheck = false;//其他的位置为false
      }
    }
    _this.setState({
      bmtetlist:bmtetlist,
      paytypes:checked
    })
  }
  closepay(){
    var _this = this
    _this.setState({
      zftype:0
    })
  }
  inputNum(type,event){
    var _this = this
    // console.log(JSON.stringify(event))
    // console.log(type)
    var paypwd = _this.state.paypwd
    if (type == 1) {
      var paypwdlen = paypwd.length
      if (paypwdlen < 6) {
        var num = event.target.dataset.number
        paypwd.push(num)
        var paypwdlen = paypwd.length
        _this.setState({
          paypwd:paypwd,
          paypwdlen:paypwdlen
        },function(){
          if (paypwdlen == 6) {
            //支付
            var payAmount = _this.state.totalAmount
            var orderId = _this.state.orderId
            _this.pay(orderId, payAmount, '')
          }
        }) 
      }
    } else if (type == 2) {
      paypwd.pop()
      var paypwdlen = paypwd.length
      _this.setState({
        paypwd:paypwd,
        paypwdlen:paypwdlen
      })
    }
    // console.log(JSON.stringify(_this.state.paypwd))
  }
  buzhichi(){
    Taro.showModal({
      title: '提示',
      content: '抱歉，小程序不允许你访问网页链接，如需获得最全功能和更好体验请下载“蝌蚪社区”APP!',
      showCancel: false
    })
  }
  render () {
    //<View className='qun-liuyan'>
    //  <Input className='' cursorSpacing='10px' maxLength='250' type='text' placeholder='给商家的备注(选填)'/>
    //</View>
    const arr = this.state.arr
    const receipt = this.state.receipt
    const bmtetlist = this.state.bmtetlist
    const tuitable = this.state.tuitable
    const paypwdlen = this.state.paypwdlen
    return (
      <View className='page'>
        <View className='qun-zffixed' style={this.state.zftype==1?'display:block':'display:none'}>
          <View className='qun-zfbotn'>
            <View className='section'>
              <View className='qun-zftite'>
                <Image className='qun-zfclose' onClick={this.closepay.bind(this)} src='https://minichat.g2ma.com/kedouimg/close1.png'></Image>
                <Text>请输入支付密码</Text>
                <Text></Text>
              </View>
              <View className='qun-zfmima'>
                <View className='qun-zfkuan'>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 1 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 2 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 3 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 4 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 5 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 6 ? '●' : ''} type='text' disabled='true'/>
                </View>
              </View>
              <View className='qun-zfwanji'><Text onClick={this.buzhichi.bind(this)}>忘记密码?</Text></View>
              <View className='tui-table-view'>
                {tuitable.map((item, index) => (
                <View className={item.tuibg ? 'tui-col-3 tui-bg' : 'tui-col-3'} dataNumber={item.number} onClick={this.inputNum.bind(this,item.click)}>
                  {item.innerhtml ?
                    <Image className='qun-zfdel' src='https://minichat.g2ma.com/kedouimg/del.png'></Image>
                    :
                    item.number
                  }
                </View>
                ))}
              </View>
            </View>
          </View>
        </View>
        <View className='qun-bgbanner'>

          <View className='qun-sohofs'>
            <View className='qun-pkzhifu'>收货方式</View>
            <View className='qun-bmgue'>
              <View classNme='qun-zifans'>
                <View className='qun-zifuli'>
                  <View className='qun-fasi'>
                    <Image mode="scaleToFill" className='qun-wlglimg' src='https://minichat.g2ma.com/kedouimg/wlgl.png'></Image>
                    <View className='qun-wexm'>
                      <Text>物流配送</Text>
                    </View>
                  </View>
                  <Image mode="scaleToFill" className='qun-bmbgtus' src='https://minichat.g2ma.com/kedouimg/checkc.png'></Image>
                </View>
              </View>
            </View>
          </View>

          <View className='qun-shouhodl' onClick={this.opendetails.bind(this,'/pages/my/address',1)}>
            <View className='qun-diliwzs'>
              <Image mode="scaleToFill" className='qun-diliwzsimg' src='https://minichat.g2ma.com/kedouimg/dingwei.png'></Image>
            </View>
            <View className='qun-dilisonr'>
              <View className='qun-dizhzojn'>
                <Text decode='true'>姓名:&nbsp;&nbsp;{receipt.name}</Text>
                <Text>{receipt.mobile == null ? receipt.phone : receipt.mobile}</Text>
              </View>
              <View className='qun-shohudizhi'>
                <Text decode='true'>收货地址:&nbsp;&nbsp;{receipt.regionName}{receipt.address}</Text>
              </View>
            </View>
            <View className='qun-dilixuze'>
              <Image mode="scaleToFill" className='qun-dilixuzeimg' src='https://minichat.g2ma.com/kedouimg/goselect.png'></Image>
            </View>
          </View>

          <View className='qun-sohofs'>
            <View className='qun-pkzhifu'>支付方式</View>
            {bmtetlist.map((item, index) => (
            <View className='qun-bmgue' onClick={this.payment.bind(this)} dataType={item.id}>
              <View classNme='qun-zifans'>
                <View className='qun-zifuli'>
                  <View className='qun-fasi'>
                    <Image mode="scaleToFill" className='qun-fsimg' src={item.touimg}></Image>
                    <View className='qun-wexm'>
                      <Text>{item.toutype}</Text>
                    </View>
                  </View>
                  <Image mode="scaleToFill" className='qun-bmbgtu' src={item.toucheck ?'https://minichat.g2ma.com/kedouimg/icon24.png' : 'https://minichat.g2ma.com/kedouimg/icon23.png'}></Image>
                </View>
              </View>
            </View>
            ))}
          </View>
          <View className='qun-hegs'></View>
          {arr.map((item, index) => (
            <View className='qun-sujuzon'>
              <View className='qun-sujus'>
                <View className='qun-tobuig'>
                  <Image mode="widthFix" className='qun-mendnimg' src='https://minichat.g2ma.com/kedouimg/store.png'></Image>
                  <Text className='qun-mendnce'>{item.shopName}</Text>
                </View>
              </View>
              <View className='qun-zongsju'>
                <View className='qun-gmtup'>
                  <Image mode="widthFix" className='qun-gmtupimg' src={item.logo}></Image>
                </View>
                <View className='qun-gminfo'>
                  <View className='qun-gmbtit'>{item.commodityName}</View>
                  <View className='qun-gmguge'>
                    <View className='qun-dspy'>规格: {item.goodsName}</View>
                    <View className='qun-dspy qun-ynfus'>运费: <Text className='coloryufu'>{this.state.yunfei}</Text></View>
                  </View>
                </View>
                <View className='qun-gmprice'>
                  <View className='qun-pricesy'>￥{this.price(item.price)}</View>
                  <View className='qun-sulan qun-gmguge'>x{item.amount}</View>
                </View>
              </View>
            </View>
          ))}
          <View className='qun-gmbom'>
            <View className='qun-gmyfje'>
              应付金额: ￥
              <Text className='qun-gmcol'>{this.totalPrice(arr[0].price,arr[0].amount)}</Text>
              (含邮费: ￥
              <Text className='qun-gmcol'>{this.state.youfui}</Text>
              )
            </View>
            <View className='qun-gmtjdd' onClick={this.getcode.bind(this)}>提交订单</View>
          </View>

        </View>
      </View>
    )
  }
}

 